package apportioner

import (
	// "bp/cache"
	sqlc "bp/db/sqlc"
	"fmt"
	// "bp/internal/util"
)

type OffCompareKey string
type OffTrialItemToOffTransactionDetailMap map[OffCompareKey][]*sqlc.OffTransactionDetail
type OffTrialItemKeyFunc func(*sqlc.OffTrialItem) OffCompareKey
type OffTransactionDetailKeyFunc func(*sqlc.OffTransactionDetail) OffCompareKey
type UpsertOffApportionmentParamsKeyFunc func(*sqlc.UpsertOffApportionmentParams) OffCompareKey

func (s *ApportionerComServiceImp) ConvOffTrialItemMapToOffTransactionDetail(
	listAsKey []*sqlc.OffTrialItem,
	listAsVal []*sqlc.OffTransactionDetail,
	keyFunc OffTrialItemKeyFunc,
	compareFunc func(*sqlc.OffTransactionDetail, OffCompareKey) bool,
) (r OffTrialItemToOffTransactionDetailMap) {
	r = make(OffTrialItemToOffTransactionDetailMap)
	for _, it := range listAsKey {
		k := keyFunc(it)
		if _, ok := r[k]; !ok {
			r[k] = []*sqlc.OffTransactionDetail{}
		}
		for _, vit := range listAsVal {
			if compareFunc(vit, k) {
				r[k] = append(r[k], vit)
			}
		}
	}
	return
}

func (s *ApportionerComServiceImp) ExtractOwnerOffTrialItemKey(ownerID int64) OffTrialItemKeyFunc {
	return func(oti *sqlc.OffTrialItem) OffCompareKey {
		return OffCompareKey(fmt.Sprintf("%d-%d-%d", ownerID, oti.ItemID, oti.ItemSpecID))
	}
}

func (s *ApportionerComServiceImp) ExtractOwnerOffTransactionDetailKey() OffTransactionDetailKeyFunc {
	return func(otd *sqlc.OffTransactionDetail) OffCompareKey {
		return OffCompareKey(fmt.Sprintf("%d-%d-%d", otd.OwnerID, otd.ItemID, otd.ItemSpecID))
	}
}

func (s *ApportionerComServiceImp) ExtractOwnerUpsertOffApportionmentParamsKey() UpsertOffApportionmentParamsKeyFunc {
	return func(oa *sqlc.UpsertOffApportionmentParams) OffCompareKey {
		return OffCompareKey(fmt.Sprintf("%d-%d-%d", oa.OwnerID, oa.ItemID, oa.ItemSpecID))
	}
}

func (s *ApportionerComServiceImp) ConvOffTrialItemPtrsToMap(ownerID int64, ptrs []*sqlc.OffTrialItem) (r OffCompareKeyToOffTrialItemPtrMap) {
	r = make(OffCompareKeyToOffTrialItemPtrMap)
	for _, ptr := range ptrs {
		k := s.ExtractOwnerOffTrialItemKey(ownerID)(ptr)
		r[k] = ptr
	}
	return
}